#include "output.h"

void ini_output( output *op, dictionary *dict ){

    op->fp_xe       = NULL;
    op->fp_xe_rhs   = NULL;
    int save_xe     = 0;
    int save_xe_rhs = 0;

    char *out_dir = (char*)iniparser_getstring(dict, "OUTPUT:out_dir", "./");

    save_xe     = iniparser_getint(dict, "OUTPUT:save_xe", 0);
    save_xe_rhs = iniparser_getint(dict, "OUTPUT:save_xe_rhs", 0);

    if( save_xe == 0 ){
        printf("> Xe data will not be saved!\n");
    } else if( save_xe == 1 ){
        char *fname = (char*)iniparser_getstring(dict, "OUTPUT:outfile_xe", NULL);
        
        if( fname == NULL ){
            printf("outfile_xe is NOT provided!\n");
            exit(0);
        }
        
        strcpy(op->fname_xe, out_dir);
        strcat(op->fname_xe, "/");
        strcat(op->fname_xe, fname);
        op->fp_xe = fopen(op->fname_xe, "w");
    }
    
    if( save_xe_rhs == 0 ){
        printf("> Xe_rhs data will not be saved!\n");
    } else if( save_xe_rhs == 1 ){
        char *fname = (char*)iniparser_getstring(dict, "OUTPUT:outfile_xe_rhs", NULL);
    
        if( fname == NULL ){
            printf("outfile_xe_rhs is NOT provided!\n");
            exit(0);
        }
        
        strcpy(op->fname_xe_rhs, out_dir);
        strcat(op->fname_xe_rhs, "/");
        strcat(op->fname_xe_rhs, fname);
        op->fp_xe_rhs = fopen(op->fname_xe_rhs, "w");
        
        if( op->fp_xe_rhs != NULL ){
            fprintf(op->fp_xe_rhs, "#   z   ln(a)   Xe   dXe/dlna\n");
        }
    }
    
    sprintf(op->out_dir, "%s", out_dir);
    
    printf("--> initialized struct output.\n");
}

void free_output( output *op ){

    if( op->fp_xe != NULL ){
        fclose(op->fp_xe);
        op->fp_xe = NULL;
    }

    if( op->fp_xe_rhs != NULL ){
        fclose(op->fp_xe_rhs);
        op->fp_xe_rhs = NULL;
    }
    
    printf("--> cleaned strcut output.\n");
}
